package edu.neu.cloud_factory.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import edu.neu.cloud_factory.dao.ProductTypeMapper;
import edu.neu.cloud_factory.entity.po.Product;
import edu.neu.cloud_factory.dao.ProductMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.neu.cloud_factory.entity.po.ProductType;
import edu.neu.cloud_factory.entity.vo.ProductTypeVo;
import edu.neu.cloud_factory.entity.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 产品 服务实现类
 * </p>
 *
 * @author halozhy
 * @since 2021-07-15
 */
@Service
public class ProductService extends ServiceImpl<ProductMapper, Product> implements IService<Product> {
    @Autowired
    ProductMapper productMapper;

    @Autowired
    ProductTypeService productTypeService;

    public List<Product> selectProductByProductTypeId(int ptId) {
        // 查询产品类型下已关联的产品
        Map<String, Object> colMap = new HashMap<>();
        colMap.put("p_type_id", ptId);
        return productMapper.selectByMap(colMap);
    }

    public JSONObject listProd(Integer page, Integer limit, String id, String name, String describe) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        if (id != null && !id.isEmpty()) {
            queryWrapper.like("p_id", id);
        }
        if (name != null && !name.isEmpty()) {
            queryWrapper.like("p_name", name);
        }
        if (describe != null && !describe.isEmpty()) {
            queryWrapper.like("p_describe", describe);
        }

        List<Product> productList = productMapper.listPage((page - 1) * limit, limit, queryWrapper);
        List<ProductVo> productVoList = new ArrayList<>();
        List<ProductType> productTypeList = productTypeService.list();
        productList.forEach(product -> {
            ProductVo productVo = new ProductVo();
            productVo.setId(product.getPId());
            productVo.setName(product.getPName());
            productVo.setSpec(product.getPSpec());
            productVo.setDescribe(product.getPDescribe());
            productVo.setType_id(product.getPTypeId());
            for (ProductType pt :
                    productTypeList) {
                if(pt.getPtId().equals(product.getPTypeId())){
                    productVo.setType_name(pt.getPtName());
                    break;
                }
            }
            productVoList.add(productVo);
        });
        JSONObject result = new JSONObject();
        result.put("data", productVoList);
        result.put("count", productMapper.selectCount(queryWrapper));
        return result;
    }
}
